package com.even.okhttp.helper.library

import okhttp3.OkHttpClient

class OkHttpClientBuilder {

    companion object {

        //var CertificatesCache: SoftReference<HandshakeCertificates>? = null

        /** 获取握手证书对象（HandshakeCertificates），该对象用于完成与服务器的Https通信握手时的认证，包含双向认证，可查看HandshakeCertificates的文档声明 */
        /*fun getHandshakeCertificates(): HandshakeCertificates {
            var handshakeCertificates = CertificatesCache?.get()
            if (handshakeCertificates != null) {
                Timber.i("从缓存取到了证书")
                return handshakeCertificates
            }

            val certificateFactory: CertificateFactory = CertificateFactory.getInstance("X.509")
            val localCertificate = certificateFactory.generateCertificate(App.sContext.resources.openRawResource(R.raw.dazhou)) as X509Certificate
            handshakeCertificates = HandshakeCertificates.Builder()
                .addTrustedCertificate(localCertificate) // 信任指定的自定义证书
                .addPlatformTrustedCertificates()  // 信任系统的预装证书，如果不信任系统证书的话，比如在访问https://m.baidu.com时将会出错
                .build()
            CertificatesCache = SoftReference(handshakeCertificates)
            Timber.i("创建新证书")
            return handshakeCertificates
        }*/

        /** 创建一个OkHttpClient.Builder对象，会判断Android版本如果小于Android N（7.0）,则进行证书配置 */
        fun createOkHttpClientBuilder(): OkHttpClient.Builder {
            val builder = OkHttpClient.Builder()
            /*if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                    // 我们定义签名的证书在Android7.x系统中有Bug，无法完成认证，所以直接忽略
                    builder.sslSocketFactory(IgnoreAllCertUtil.sSLSocketFactory, IgnoreAllCertUtil.trustManager)
                    Timber.i("Android 7.x，忽略证书")
                } else {
                    val certificates = getHandshakeCertificates()
                    builder.sslSocketFactory(certificates.sslSocketFactory(), certificates.trustManager)
                    Timber.i("Android 7.0以下的系统")
                }
            }*/
            return builder
            // 要实现双向认证，可参考：https://github.com/hongyangAndroid/okhttputils
        }

    }

}